<template>
  <div>
    <!--关联该组件（一定要小写）-->
    <v-form v-model="valid" ref="myBrandForm">
      <v-text-field label="请输入品牌名称" v-model="brand.name"  :rules="nameRules" counter="3" required></v-text-field>
      <v-text-field label="请输入品牌首字母" v-model="brand.letter" :rules="letterRules" required></v-text-field>
    <v-cascader
      url="/item/category/list"
      multiple
      required
      v-model="brand.categories"
      label="请选择商品分类"/>
    <v-layout row>
      <v-flex xs3>
        <span style="font-size: 16px; color: #444">品牌LOGO：</span>
      </v-flex>
      <v-flex>
        <v-upload
          v-model="brand.image"
          url="/upload/image"
          :multiple="false"
          :pic-width="250"
          :pic-height="90"
        />
      </v-flex>
    </v-layout>
    <v-btn @click="submit">提交</v-btn>
     <v-btn @click="clear">重置</v-btn>
    </v-form>
  </div>
</template>

<script>
export default {
  name: "my-brand-form",
  props:{
    oldBrand:{
      type:Object
    },
    edit:{
      type: Boolean,
      default:false
    }
  },
  data() {
    return {
      valid:false,
      brand:{
        name:'', // 品牌名称
        letter:'', // 品牌首字母
        image:'',// 品牌logo
        categories:[], // 品牌所属的商品分类数组
      },
      nameRules:[
        v => !!v || "品牌名称不能为空",
        v => v.length > 1 || "品牌名称至少2位"
      ],
      letterRules:[
        v => !!v || "首字母不能为空",
        v => /^[A-Z]{1}$/.test(v) || "品牌字母只能是A~Z的大写字母,并且只能写一个"
      ]
    }
  },
  watch:{
    oldBrand:{
      handler(val){
        if(val){
          this.brand=Object.deepCopy(val);
        }
        else{
          this.brand = {
            name: '',
            letter: '',
            image: '',
            categories: [],
          }
        }
      }
    },
    deep:true
  },
  methods:{
    submit(){
      // 提交表单
     // 把brand里的categories数组单独取出，得到id
     let {categories,...param}=this.brand;
      // 数据库中只要保存分类的id即可，因此我们对categories的值进行处理,只保留id，并转为字符串
      categories=categories.map(category=>category.id);
      param.cids = categories.join(",");
      this.$http({
          method: this.edit ?"put":"post",
          url:"/item/brand",
          data:this.$qs.stringify(param)
        }
      ) .then(resp=>{

        if(this.edit){
          this.$message.success("品牌修改成功");
        }else{
          this.$message.success("品牌添加成功");
        }
        this.$emit("close");

      }).catch(resp=>{

        this.$message.error(this.isEdit?"修改":"新增" + "品牌失败");

      })
    },
    clear(){
      // 重置表单
      this.$refs.myBrandForm.reset();
      // 需要手动清空商品分类
      this.brand.categories = [];
    },
  }
}
</script>

<style scoped>

</style>
